package middleware

import (
	"bytes"
	"log"
	"net/http"
)

func AuthMiddleware() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			log.Printf("HttpMethod: [%s],HttpRequestURI: [%s]\n", r.Method, r.URL.Path)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			// 创建一个缓冲区来存储响应内容
			buf := &bytes.Buffer{}
			writer := &responseWriterWithCallback{
				ResponseWriter: w,
				buf:            buf,
				callback: func(body []byte) {
					log.Printf("HttpRequestURI: [%s],Result: %s\n", r.URL.Path, string(body))
				},
			}
			next.ServeHTTP(writer, r)
			writer.flush()
		})
	}
}

// 响应回调函数类型
type ResponseCallback func(body []byte)

// 自定义的 ResponseWriter 带有回调
type responseWriterWithCallback struct {
	http.ResponseWriter
	buf      *bytes.Buffer
	callback ResponseCallback
}

// Write 重写 Write 方法，将响应内容写入缓冲区
func (r *responseWriterWithCallback) Write(b []byte) (int, error) {
	return r.buf.Write(b)
}

// flush 在响应完成后调用回调函数
func (r *responseWriterWithCallback) flush() {
	if r.callback != nil {
		r.callback(r.buf.Bytes())
	}
	// 将缓冲区内容写入原始的 ResponseWriter
	r.ResponseWriter.Write(r.buf.Bytes())
}
